package com.zsk.okhttp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

import com.alibaba.fastjson.JSON;

import okhttp3.Response;
import okhttp3.internal.Util;

/**
 *
 * @author keke
 * @date 2020/04/23
 */
public class ResData {

    private Response response;

    public ResData() {

    }

    public ResData(Response response) {
        this.response = response;
    }

    public static ResData of(Response response) {
        return new ResData(response);
    }

    public <T> T toBean(Class<T> clazz) throws IOException {
        return JSON.parseObject(response.body().string(), clazz);
    }

    public <T> T toBean(String json, Class<T> clazz) {
        return JSON.parseObject(json, clazz);
    }

    public String toStr() throws IOException {
        return response.body().string();
    }

    /**
     * 将响应转换为文件，下载进度监听支持null
     * 
     * @param filePath
     * @param listener
     * @return
     */
    public boolean toFile(String filePath, PercentListener listener) {
        return toFile(response, filePath, listener);
    }

    public static boolean toFile(Response response, String filePath, PercentListener listener) {
        byte[] buf = new byte[1024];
        FileOutputStream fos = null;
        try {
            File file = new File(filePath);
            File dir = file.getParentFile();
            if (dir != null && dir.isDirectory()) {
                dir.mkdirs();
            }
            InputStream is = response.body().byteStream();
            long total = response.body().contentLength();
            fos = new FileOutputStream(file);
            long sum = 0;
            int progress = 0;
            int len = 0;
            int prePercent = 0;
            while ((len = is.read(buf)) != -1) {
                fos.write(buf, 0, len);
                sum += len;
                progress = (int)(sum * 1.0 / total * 100);
                // update download percent
                if (listener != null && progress > prePercent) {
                    listener.process(progress);
                    prePercent = progress;
                }
            }
            fos.flush();
            progress = 100;
            if (listener != null && progress > prePercent) {
                listener.process(progress);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Util.closeQuietly(fos);
        }
        return false;
    }

    public byte[] toBytes() throws IOException {
        return response.body().bytes();
    }

    public String toBase64Str() throws IOException {
        return Base64.getEncoder().encodeToString(response.body().bytes());
    }

    public boolean ok() {
        return response.isSuccessful();
    }

    public void close() {
        response.close();
    }

    /**
     * 
     * @author keke
     * @date 2020/04/23
     */
    public static interface PercentListener {
        /**
         * 进度监听
         * 
         * @param percent
         */
        void process(int percent);
    }

}
